$(document).ready(function() {
    const $captchaInput = $('#captcha');
    const $captchaImage = $('#captchaImage');
    const $refreshBtn = $('.refresh-btn');
    const $loginBtn = $('#loginBtn');
    const $loginForm = $('#loginForm');

    let currentCaptcha = '';
    let isVerified = false;
    let autoRefreshTimer;

    // IndexedDB初始化
    let db;
    const dbName = 'UserDB';
    const dbVersion = 1;
    
    const request = indexedDB.open(dbName, dbVersion);
    
    request.onerror = function(event) {
        console.error('数据库错误：', event.target.error);
    };
    
    request.onsuccess = function(event) {
        db = event.target.result;
        console.log('数据库连接成功');
    };
    
    request.onupgradeneeded = function(event) {
        db = event.target.result;
        if (!db.objectStoreNames.contains('users')) {
            const store = db.createObjectStore('users', { keyPath: 'username' });
            store.createIndex('email', 'email', { unique: true });
            console.log('用户表创建成功');
        }
    };

    // 切换表单显示
    $('.switch-btn').on('click', function() {
        const formType = $(this).data('form');
        $('.switch-btn').removeClass('active');
        $(this).addClass('active');
        
        if (formType === 'login') {
            $('#loginForm').fadeIn(300).addClass('form-active');
            $('#registerForm').fadeOut(300).removeClass('form-active');
            refreshCaptcha();
        } else {
            $('#registerForm').fadeIn(300).addClass('form-active');
            $('#loginForm').fadeOut(300).removeClass('form-active');
            initRegisterForm();
        }
    });

    // 注册表单验证
    const $regUsername = $('#reg-username');
    const $regPassword = $('#reg-password');
    const $regConfirmPassword = $('#reg-confirm-password');
    const $regEmail = $('#reg-email');
    const $regCaptcha = $('#reg-captcha');
    const $regCaptchaImage = $('#regCaptchaImage');
    const $registerBtn = $('#registerBtn');
    let regCaptchaCode = '';

    const $regPhone = $('#reg-phone');
    const $regPhoneCode = $('#reg-phone-code');
    const $sendCodeBtn = $('#sendCodeBtn');
    let phoneVerified = false;
    let currentPhoneCode = '';
    let countdown = 60;
    let countdownTimer;

    // 手机号码验证
    function validatePhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    }

    // 开始倒计时
    function startCountdown() {
        $sendCodeBtn.addClass('disabled');
        countdown = 60;
        updateCountdownText();
        
        countdownTimer = setInterval(() => {
            countdown--;
            updateCountdownText();
            
            if (countdown <= 0) {
                clearInterval(countdownTimer);
                $sendCodeBtn.removeClass('disabled').text('获取验证码');
            }
        }, 1000);
    }

    // 更新倒计时文本
    function updateCountdownText() {
        $sendCodeBtn.text(`重新发送(${countdown}s)`);
    }

    // 生成手机验证码
    function generatePhoneCode() {
        let code = '';
        for(let i = 0; i < 6; i++) {
            code += Math.floor(Math.random() * 10);
        }
        return code;
    }

    // 发送验证码按钮点击事件
    $sendCodeBtn.on('click', function() {
        if ($(this).hasClass('disabled')) return;
        
        const phone = $regPhone.val();
        if (!validatePhone(phone)) {
            showError($regPhone, '请输入正确的手机号码');
            return;
        }

        // 生成验证码
        currentPhoneCode = generatePhoneCode();
        console.log('验证码：', currentPhoneCode); // 实际项目中应该通过短信发送
        
        // 开始倒计时
        startCountdown();
        
        // 这里应该调用短信发送API
        alert(`验证码已发送：${currentPhoneCode}`);
    });

    // 验证手机验证码
    $regPhoneCode.on('input', function() {
        const input = $(this).val();
        $(this).removeClass('valid invalid');
        
        if(input.length === 6) {
            if(input === currentPhoneCode) {
                $(this).addClass('valid');
                phoneVerified = true;
                validateAllFields();
            } else {
                $(this).addClass('invalid');
                phoneVerified = false;
                validateAllFields();
                showError($(this), '验证码错误');
            }
        } else {
            phoneVerified = false;
            validateAllFields();
        }
    });

    // 手机号码输入验证
    $regPhone.on('input', function() {
        const phone = $(this).val();
        if (phone.length === 11 && !validatePhone(phone)) {
            showError($(this), '请输入正确的手机号码');
        }
    });

    // 验证所有字段以启用/禁用注册按钮
    function validateAllFields() {
        const username = $regUsername.val().trim();
        const password = $regPassword.val();
        const confirmPassword = $regConfirmPassword.val();
        const email = $regEmail.val().trim();
        const phone = $regPhone.val().trim();
        const phoneCode = $regPhoneCode.val();
        const captcha = $regCaptcha.val().toUpperCase();

        // 检查是否有错误提示
        const hasErrors = $('.form-error:visible').length > 0;
        
        // 检查所有字段是否有效
        const isUsernameValid = username.length >= 4;
        const isPasswordValid = password.length >= 6;
        const isConfirmPasswordValid = password === confirmPassword;
        const isEmailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
        const isPhoneValid = validatePhone(phone);
        const isPhoneCodeValid = phoneVerified && phoneCode === currentPhoneCode;
        const isCaptchaValid = captcha === regCaptchaCode;

        const isValid = isUsernameValid &&
                       isPasswordValid &&
                       isConfirmPasswordValid &&
                       isEmailValid &&
                       isPhoneValid &&
                       isPhoneCodeValid &&
                       isCaptchaValid &&
                       !hasErrors;

        if (isValid) {
            $registerBtn.prop('disabled', false).addClass('active');
        } else {
            $registerBtn.prop('disabled', true).removeClass('active');
        }

        return isValid;
    }

    // 为所有输入框添加验证
    $('#registerForm input').on('input', validateAllFields);

    // 文件上传相关变量
    const $regAvatar = $('#reg-avatar');
    const $avatarPreview = $('#avatarPreview');
    const $uploadProgress = $('.upload-progress');
    const $progressFill = $('.progress-fill');
    const $progressText = $('.progress-text');
    let avatarFile = null;

    // 图片预览相关变量
    const $previewModal = $('.preview-modal');
    const $modalImage = $('#modalImage');
    const $modalOverlay = $('.modal-overlay');
    const $closeModal = $('.close-modal');
    const $zoomContainer = $('.image-zoom-container');
    const $zoomIn = $('.zoom-in');
    const $zoomOut = $('.zoom-out');
    const $resetZoom = $('.reset-zoom');
    
    // 缩放相关变量
    let currentScale = 1;
    let isDragging = false;
    let startX = 0;
    let startY = 0;
    let translateX = 0;
    let translateY = 0;

    // 修改文件上传处理，优化预览体验
    $regAvatar.on('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;

        // 验证文件类型
        if (!file.type.match(/^image\/(jpeg|png)$/)) {
            showError($(this), '只支持 jpg、png 格式的图片');
            return;
        }

        // 验证文件大小（10MB）
        const maxSize = 10 * 1024 * 1024; // 10MB in bytes
        if (file.size > maxSize) {
            showError($(this), '图片大小不能超过 10MB');
            return;
        }

        // 重置进度条
        $uploadProgress.show();
        $progressFill.css('width', '0%');
        $progressText.text('0%');

        // 创建 FileReader 实例
        const reader = new FileReader();
        
        // 监听读取进度
        reader.onprogress = function(e) {
            if (e.lengthComputable) {
                const progress = (e.loaded / e.total) * 100;
                updateProgress(progress);
                
                // 添加文件大小信息
                const totalSize = formatFileSize(e.total);
                const loadedSize = formatFileSize(e.loaded);
                $progressText.text(`${Math.round(progress)}% (${loadedSize}/${totalSize})`);
            }
        };

        // 读取完成时显示预览
        reader.onload = function(e) {
            // 创建图片对象以获取实际尺寸
            const img = new Image();
            
            img.onload = function() {
                // 更新预览图片，添加淡入效果
                $avatarPreview.stop(true).fadeOut(200, function() {
                    $(this).attr('src', e.target.result)
                           .attr('data-original-src', e.target.result) // 保存原始图片数据
                           .fadeIn(200);
                });
                
                // 完成进度条动画
                updateProgress(100);
                setTimeout(() => {
                    $uploadProgress.fadeOut();
                }, 500);
                
                // 保存文件信息
                avatarFile = file;
            };
            
            img.onerror = function() {
                showError($regAvatar, '图片加载失败，请重试');
                resetAvatarUpload();
            };
            
            img.src = e.target.result;
        };

        // 读取错误处理
        reader.onerror = function() {
            showError($regAvatar, '图片读取失败，请重试');
            resetAvatarUpload();
        };

        // 开始读取文件
        reader.readAsDataURL(file);
    });

    // 点击头像预览图片
    $avatarPreview.on('click', function() {
        const imgSrc = $(this).attr('data-original-src') || $(this).attr('src');
        // 不预览默认头像
        if (imgSrc.includes('svg')) return;
        
        // 重置缩放状态
        resetZoom();
        
        // 设置预览图片
        $modalImage.attr('src', imgSrc)
                  .css('max-width', 'none')  // 移除最大宽度限制以允许放大
                  .css('max-height', '80vh'); // 保持高度限制以适应屏幕
        
        // 显示模态框
        $previewModal.css({
            display: 'flex',
            opacity: 0
        }).animate({
            opacity: 1
        }, 300);
        
        // 禁止背景滚动
        $('body').css('overflow', 'hidden');
    });

    // 缩放功能
    $zoomIn.on('click', function() {
        if (currentScale < 3) {  // 最大放大3倍
            currentScale += 0.5;
            updateImageTransform();
        }
    });

    $zoomOut.on('click', function() {
        if (currentScale > 0.5) {  // 最小缩小0.5倍
            currentScale -= 0.5;
            updateImageTransform();
        }
    });

    $resetZoom.on('click', resetZoom);

    // 更新图片变换
    function updateImageTransform() {
        const transform = `scale(${currentScale}) translate(${translateX / currentScale}px, ${translateY / currentScale}px)`;
        $modalImage.css({
            'transform': transform,
            'transform-origin': 'center center',
            'transition': 'transform 0.2s ease-out'
        });
    }

    // 重置缩放
    function resetZoom() {
        currentScale = 1;
        translateX = 0;
        translateY = 0;
        updateImageTransform();
        $modalImage.css('cursor', 'grab');
    }

    // 拖动功能
    $modalImage.on('mousedown', function(e) {
        if (currentScale > 1) {
            isDragging = true;
            startX = e.clientX - translateX;
            startY = e.clientY - translateY;
            $modalImage.css('cursor', 'grabbing');
            e.preventDefault(); // 防止拖动时选中图片
        }
    });

    $(document).on('mousemove', function(e) {
        if (isDragging) {
            translateX = e.clientX - startX;
            translateY = e.clientY - startY;
            
            // 限制拖动范围
            const maxTranslate = (currentScale - 1) * $modalImage.width() / 2;
            translateX = Math.max(-maxTranslate, Math.min(maxTranslate, translateX));
            translateY = Math.max(-maxTranslate, Math.min(maxTranslate, translateY));
            
            updateImageTransform();
        }
    });

    $(document).on('mouseup', function() {
        if (isDragging) {
            isDragging = false;
            $modalImage.css('cursor', 'grab');
        }
    });

    // 鼠标滚轮缩放
    $zoomContainer.on('wheel', function(e) {
        e.preventDefault();
        const delta = e.originalEvent.deltaY;
        const zoomSpeed = 0.1;
        
        if (delta < 0 && currentScale < 3) {  // 放大
            currentScale = Math.min(3, currentScale + zoomSpeed);
            updateImageTransform();
        } else if (delta > 0 && currentScale > 0.5) {  // 缩小
            currentScale = Math.max(0.5, currentScale - zoomSpeed);
            updateImageTransform();
        }
    });

    // 关闭预览模态框时重置缩放
    function closePreviewModal() {
        $previewModal.animate({
            opacity: 0
        }, 300, function() {
            $(this).css('display', 'none');
            // 恢复背景滚动
            $('body').css('overflow', '');
            // 重置缩放状态
            resetZoom();
        });
    }

    // 双击图片重置缩放
    $modalImage.on('dblclick', resetZoom);

    // 修改其他事件处理程序...
    $closeModal.on('click', function(e) {
        e.stopPropagation();
        closePreviewModal();
    });

    $modalOverlay.on('click', closePreviewModal);

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $previewModal.is(':visible')) {
            closePreviewModal();
        }
    });

    // 阻止图片点击事件冒泡
    $modalImage.on('click', function(e) {
        e.stopPropagation();
    });

    // 添加文件大小格式化函数
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 更新进度条函数
    function updateProgress(progress) {
        progress = Math.min(100, Math.round(progress));
        $progressFill.css('width', `${progress}%`);
    }

    // 修改注册表单提交处理，添加文件上传
    $('#registerForm').on('submit', function(e) {
        e.preventDefault();
        
        // 再次验证所有字段
        if (!validateAllFields()) {
            return false;
        }

        const userData = {
            username: $regUsername.val().trim(),
            password: $regPassword.val(),
            email: $regEmail.val().trim(),
            phone: $regPhone.val().trim(),
            createTime: new Date().toISOString()
        };

        // 如果有上传头像，添加到用户数据中
        if (avatarFile) {
            const reader = new FileReader();
            reader.onload = function(e) {
                userData.avatar = e.target.result;
                saveUserData(userData);
            };
            reader.readAsDataURL(avatarFile);
        } else {
            saveUserData(userData);
        }
    });

    // 保存用户数据
    function saveUserData(userData) {
        const transaction = db.transaction(['users'], 'readwrite');
        const store = transaction.objectStore('users');

        // 检查用户名是否已存在
        store.get(userData.username).onsuccess = function(event) {
            if (event.target.result) {
                showError($regUsername, '用户名已存在');
                return;
            }

            // 检查邮箱是否已存在
            const emailIndex = store.index('email');
            emailIndex.get(userData.email).onsuccess = function(event) {
                if (event.target.result) {
                    showError($regEmail, '邮箱已被注册');
                    return;
                }

                // 保存用户数据
                store.add(userData).onsuccess = function() {
                    alert('注册成功！');
                    
                    // 清除所有定时器
                    if (countdownTimer) {
                        clearInterval(countdownTimer);
                    }
                    
                    // 重置表单状态
                    $('#registerForm')[0].reset();
                    $('.form-error').hide();
                    $('.input-error').removeClass('input-error');
                    $registerBtn.prop('disabled', true).removeClass('active');
                    
                    // 重置头像上传状态
                    resetAvatarUpload();
                    
                    // 切换到登录表单
                    setTimeout(() => {
                        $('.switch-btn[data-form="login"]').click();
                    }, 1000);
                };
            };
        };
    }

    // 修改重置头像上传状态函数
    function resetAvatarUpload() {
        $avatarPreview.fadeOut(200, function() {
            $(this).attr('src', 'data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'120\' height=\'120\' viewBox=\'0 0 120 120\'%3E%3Crect width=\'120\' height=\'120\' fill=\'%23f0f0f0\'/%3E%3Cpath d=\'M60 40c11 0 20 9 20 20s-9 20-20 20-20-9-20-20 9-20 20-20zm0-8c-15.5 0-28 12.5-28 28s12.5 28 28 28 28-12.5 28-28-12.5-28-28-28z\' fill=\'%23ccc\'/%3E%3C/svg%3E')
                   .removeAttr('data-original-src')
                   .fadeIn(200);
        });
        avatarFile = null;
        $uploadProgress.hide();
        $progressFill.css('width', '0%');
        $progressText.text('0%');
    }

    // 修改初始化注册表单函数
    function initRegisterForm() {
        // 清空所有输入
        $('#registerForm')[0].reset();
        
        // 清除所有错误提示
        $('.form-error').hide();
        $('.input-error').removeClass('input-error');
        
        // 禁用注册按钮
        $registerBtn.prop('disabled', true).removeClass('active');
        
        // 重置手机验证码状态
        phoneVerified = false;
        currentPhoneCode = '';
        $sendCodeBtn.removeClass('disabled').text('获取验证码');
        if (countdownTimer) {
            clearInterval(countdownTimer);
        }
        
        // 重置头像上传状态
        resetAvatarUpload();
        
        // 刷新验证码
        refreshRegCaptcha();
    }

    // 注册验证码相关函数
    function refreshRegCaptcha() {
        regCaptchaCode = generateCaptcha();
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = 140;
        canvas.height = 46;

        // 绘制背景
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        gradient.addColorStop(0, '#f8f9fa');
        gradient.addColorStop(1, '#e9ecef');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制干扰线
        for(let i = 0; i < 4; i++) {
            ctx.beginPath();
            ctx.strokeStyle = `rgba(${Math.random()*150},${Math.random()*150},${Math.random()*150},0.2)`;
            ctx.lineWidth = 1;
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.bezierCurveTo(
                Math.random() * canvas.width, Math.random() * canvas.height,
                Math.random() * canvas.width, Math.random() * canvas.height,
                Math.random() * canvas.width, Math.random() * canvas.height
            );
            ctx.stroke();
        }

        // 绘制干扰点
        for(let i = 0; i < 60; i++) {
            ctx.fillStyle = `rgba(${Math.random()*150},${Math.random()*150},${Math.random()*150},0.2)`;
            ctx.beginPath();
            ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 
                   Math.random() * 2, 0, 2 * Math.PI);
            ctx.fill();
        }

        // 绘制验证码文字
        ctx.textBaseline = 'middle';
        for(let i = 0; i < regCaptchaCode.length; i++) {
            const fontSize = Math.floor(Math.random() * 4) + 22;
            const x = 25 + i * 28;
            const y = canvas.height / 2 + (Math.random() * 6 - 3);
            
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate((Math.random() - 0.5) * 0.4);
            
            const textGradient = ctx.createLinearGradient(-10, -10, 10, 10);
            textGradient.addColorStop(0, `rgb(${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)})`);
            textGradient.addColorStop(1, `rgb(${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)})`);
            
            ctx.font = `bold ${fontSize}px Arial`;
            ctx.fillStyle = textGradient;
            ctx.fillText(regCaptchaCode[i], 0, 0);
            
            ctx.shadowColor = 'rgba(0,0,0,0.1)';
            ctx.shadowBlur = 2;
            ctx.shadowOffsetX = 1;
            ctx.shadowOffsetY = 1;
            
            ctx.restore();
        }

        $regCaptchaImage.fadeOut(100, function() {
            $(this).attr('src', canvas.toDataURL('image/png'))
                   .fadeIn(100);
        });
    }

    // 显示错误信息函数
    function showError($input, message) {
        const $formGroup = $input.closest('.form-group');
        let $error = $formGroup.find('.form-error');
        
        if ($error.length === 0) {
            $error = $('<div class="form-error"></div>');
            $formGroup.append($error);
        }
        
        $input.addClass('input-error').addClass('shake');
        $error.text(message).fadeIn(200);
        
        setTimeout(() => {
            $input.removeClass('shake');
        }, 300);
    }

    // 清除错误信息
    function clearError($input) {
        const $formGroup = $input.closest('.form-group');
        $input.removeClass('input-error');
        $formGroup.find('.form-error').fadeOut(200);
    }

    // 实时验证用户名
    $regUsername.on('input', function() {
        const username = $(this).val();
        clearError($(this));
        
        if (username.length >= 4) {
            const transaction = db.transaction(['users'], 'readonly');
            const store = transaction.objectStore('users');
            const request = store.get(username);
            
            request.onsuccess = function(event) {
                if (event.target.result) {
                    showError($regUsername, '用户名已存在');
                }
            };
        }
        validateAllFields();
    });

    // 实时验证密码
    $regPassword.on('input', function() {
        clearError($(this));
        const password = $(this).val();
        
        if (password.length > 0 && password.length < 6) {
            showError($(this), '密码至少需要6个字符');
        }
        validateAllFields();
    });

    // 实时验证确认密码
    $regConfirmPassword.on('input', function() {
        clearError($(this));
        const password = $regPassword.val();
        const confirmPassword = $(this).val();
        
        if (confirmPassword && password !== confirmPassword) {
            showError($(this), '两次输入的密码不一致');
        }
        validateAllFields();
    });

    // 实时验证邮箱
    $regEmail.on('input', function() {
        const email = $(this).val();
        clearError($(this));
        
        if (email) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                showError($(this), '请输入有效的邮箱地址');
            } else {
                const transaction = db.transaction(['users'], 'readonly');
                const store = transaction.objectStore('users');
                const emailIndex = store.index('email');
                const request = emailIndex.get(email);
                
                request.onsuccess = function(event) {
                    if (event.target.result) {
                        showError($regEmail, '邮箱已被注册');
                    }
                };
            }
        }
        validateAllFields();
    });

    // 实时验证手机号码
    $regPhone.on('input', function() {
        const phone = $(this).val().replace(/\D/g, '');
        $(this).val(phone); // 只允许输入数字
        clearError($(this));
        
        if (phone.length === 11) {
            if (!validatePhone(phone)) {
                showError($(this), '请输入正确的手机号码');
            }
        }
        validateAllFields();
    });

    // 注册验证码输入验证
    $regCaptcha.on('input', function() {
        const input = $(this).val().toUpperCase();
        $(this).removeClass('valid invalid');
        clearError($(this));
        
        if(input.length === 4) {
            if(input === regCaptchaCode) {
                $(this).addClass('valid');
                validateAllFields();
            } else {
                $(this).addClass('invalid');
                showError($(this), '验证码错误');
                setTimeout(() => {
                    refreshRegCaptcha();
                }, 500);
            }
        } else {
            $(this).removeClass('valid invalid');
        }
        validateAllFields();
    });

    // 为注册表单的验证码刷新按钮添加事件
    $('#registerForm .refresh-btn').on('click', function() {
        if (!$(this).hasClass('refreshing')) {
            refreshRegCaptcha();
        }
    });

    // 修改登录逻辑，验证用户信息
    $loginForm.on('submit', function(e) {
        e.preventDefault();
        if (!isVerified) {
            alert('请输入正确的验证码！');
            return;
        }
        
        const username = $('#username').val();
        const password = $('#password').val();
        
        if (!username || !password) {
            alert('请输入账号和密码！');
            return;
        }

        // 验证用户登录信息
        const transaction = db.transaction(['users'], 'readonly');
        const store = transaction.objectStore('users');
        const request = store.get(username);

        request.onsuccess = function(event) {
            const user = event.target.result;
            if (user && user.password === password) {
                alert('登录成功！');
                // 清除定时器
                if (autoRefreshTimer) {
                    clearInterval(autoRefreshTimer);
                }
            } else {
                alert('账号或密码错误！');
                $('#password').val('');
                refreshCaptcha();
            }
        };
    });

    // 生成随机验证码
    function generateCaptcha() {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let captcha = '';
        for(let i = 0; i < 4; i++) {
            captcha += chars[Math.floor(Math.random() * chars.length)];
        }
        return captcha;
    }

    // 添加自动刷新定时器
    function initAutoRefresh() {
        if (autoRefreshTimer) {
            clearInterval(autoRefreshTimer);
        }
        autoRefreshTimer = setInterval(() => {
            if (!$refreshBtn.hasClass('refreshing') && !isVerified) {
                refreshCaptcha();
            }
        }, 10000); // 10秒刷新一次
    }

    // 为验证码图片添加点击事件
    $captchaImage.on('click', function() {
        refreshCaptcha();
    });

    // 修改刷新验证码函数
    function refreshCaptcha() {
        const $refreshBtn = $('.refresh-btn');
        if ($refreshBtn.hasClass('refreshing')) return;

        $refreshBtn.addClass('refreshing');
        
        // 添加点击反馈动画
        $captchaImage.css('transform', 'scale(0.95)');
        setTimeout(() => {
            $captchaImage.css('transform', 'scale(1)');
        }, 100);

        currentCaptcha = generateCaptcha();
        
        // 使用Canvas绘制验证码
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = 140;  // 匹配CSS中的宽度
        canvas.height = 46;  // 匹配CSS中的高度

        // 绘制背景
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        gradient.addColorStop(0, '#f8f9fa');
        gradient.addColorStop(1, '#e9ecef');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制干扰线
        for(let i = 0; i < 4; i++) {
            ctx.beginPath();
            ctx.strokeStyle = `rgba(${Math.random()*150},${Math.random()*150},${Math.random()*150},0.2)`;
            ctx.lineWidth = 1;
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.bezierCurveTo(
                Math.random() * canvas.width, Math.random() * canvas.height,
                Math.random() * canvas.width, Math.random() * canvas.height,
                Math.random() * canvas.width, Math.random() * canvas.height
            );
            ctx.stroke();
        }

        // 绘制干扰点
        for(let i = 0; i < 60; i++) {
            ctx.fillStyle = `rgba(${Math.random()*150},${Math.random()*150},${Math.random()*150},0.2)`;
            ctx.beginPath();
            ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 
                   Math.random() * 2, 0, 2 * Math.PI);
            ctx.fill();
        }

        // 绘制验证码文字
        ctx.textBaseline = 'middle';
        for(let i = 0; i < currentCaptcha.length; i++) {
            const fontSize = Math.floor(Math.random() * 4) + 22; // 20-24px随机字体大小
            const x = 25 + i * 28;
            const y = canvas.height / 2 + (Math.random() * 6 - 3);
            
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate((Math.random() - 0.5) * 0.4);
            
            // 创建文字渐变色
            const textGradient = ctx.createLinearGradient(-10, -10, 10, 10);
            textGradient.addColorStop(0, `rgb(${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)})`);
            textGradient.addColorStop(1, `rgb(${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)},${Math.floor(Math.random()*100)})`);
            
            ctx.font = `bold ${fontSize}px Arial`;
            ctx.fillStyle = textGradient;
            ctx.fillText(currentCaptcha[i], 0, 0);
            
            // 添加文字阴影
            ctx.shadowColor = 'rgba(0,0,0,0.1)';
            ctx.shadowBlur = 2;
            ctx.shadowOffsetX = 1;
            ctx.shadowOffsetY = 1;
            
            ctx.restore();
        }

        // 更新图片并添加过渡动画
        $captchaImage.fadeOut(100, function() {
            $(this).attr('src', canvas.toDataURL('image/png'))
                   .fadeIn(100);
        });
        
        // 重置输入和状态
        $captchaInput.val('').focus();
        isVerified = false;
        $loginBtn.prop('disabled', true).removeClass('active');

        // 重置定时器
        initAutoRefresh();

        setTimeout(() => {
            $refreshBtn.removeClass('refreshing');
        }, 500);
    }

    // 验证码输入验证
    $captchaInput.on('input', function() {
        const input = $(this).val().toUpperCase();
        $(this).removeClass('valid invalid');
        
        if(input.length === 4) {
            if(input === currentCaptcha) {
                isVerified = true;
                $loginBtn.prop('disabled', false).addClass('active');
                $(this).addClass('valid');
            } else {
                isVerified = false;
                $loginBtn.prop('disabled', true).removeClass('active');
                $(this).addClass('invalid');
                setTimeout(() => {
                    refreshCaptcha();
                }, 500);
            }
        } else {
            isVerified = false;
            $loginBtn.prop('disabled', true).removeClass('active');
            $(this).removeClass('valid invalid');
        }
    });

    // 刷新按钮点击事件
    $refreshBtn.on('click', function() {
        if (!$(this).hasClass('refreshing')) {
            refreshCaptcha();
        }
    });

    // 页面卸载时清理定时器
    $(window).on('unload', function() {
        if (autoRefreshTimer) {
            clearInterval(autoRefreshTimer);
        }
        if (countdownTimer) {
            clearInterval(countdownTimer);
        }
    });

    // 初始化验证码和自动刷新
    refreshCaptcha();

    // 内存监控相关变量
    let memoryChart = null;
    let processChart = null;
    let memoryTimer = null;
    const maxDataPoints = 30; // 最多显示30个数据点
    let memoryData = [];
    let timeData = [];
    let processData = [];

    // 初始化内存监控图表
    function initMemoryCharts() {
        // 总体内存趋势图
        const trendChartDom = document.getElementById('memoryTrendChart');
        memoryChart = echarts.init(trendChartDom);
        
        const trendOption = {
            grid: {
                top: 30,
                right: 20,
                bottom: 30,
                left: 60
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    const memory = params[0].value;
                    return `${params[0].axisValue}<br/>
                            总内存使用: ${formatMemorySize(memory)}`;
                }
            },
            xAxis: {
                type: 'category',
                data: timeData,
                axisLabel: {
                    formatter: function(value) {
                        return value.substring(value.indexOf(' ') + 1);
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: '内存使用',
                axisLabel: {
                    formatter: function(value) {
                        return formatMemorySize(value);
                    }
                }
            },
            series: [{
                name: '内存使用',
                type: 'line',
                smooth: true,
                data: memoryData,
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(102, 126, 234, 0.5)'
                    }, {
                        offset: 1,
                        color: 'rgba(118, 75, 162, 0.1)'
                    }])
                },
                lineStyle: {
                    width: 2,
                    color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
                        offset: 0,
                        color: '#667eea'
                    }, {
                        offset: 1,
                        color: '#764ba2'
                    }])
                },
                itemStyle: {
                    color: '#667eea',
                    borderWidth: 2
                }
            }]
        };
        
        memoryChart.setOption(trendOption);

        // 进程内存占用饼图
        const processChartDom = document.getElementById('processChart');
        processChart = echarts.init(processChartDom);
        
        const processOption = {
            tooltip: {
                trigger: 'item',
                formatter: function(params) {
                    return `${params.name}<br/>
                            内存占用: ${formatMemorySize(params.value)}<br/>
                            占比: ${params.percent}%`;
                }
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                formatter: function(name) {
                    const data = processOption.series[0].data;
                    const item = data.find(item => item.name === name);
                    return `${name}: ${formatMemorySize(item.value)}`;
                }
            },
            series: [{
                name: '进程内存',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['35%', '50%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false
                },
                emphasis: {
                    label: {
                        show: true,
                        formatter: '{b}: {d}%'
                    }
                },
                data: []
            }]
        };
        
        processChart.setOption(processOption);
    }

    // 更新内存数据
    function updateMemoryData() {
        // 获取当前时间
        const now = new Date();
        const timeStr = now.toLocaleTimeString();
        
        // 获取内存使用情况
        if (performance && performance.memory) {
            const totalMemory = performance.memory.usedJSHeapSize;
            
            // 添加新数据到趋势图
            memoryData.push(totalMemory);
            timeData.push(timeStr);
            
            // 保持最多显示maxDataPoints个数据点
            if (memoryData.length > maxDataPoints) {
                memoryData.shift();
                timeData.shift();
            }
            
            // 更新趋势图
            memoryChart.setOption({
                xAxis: {
                    data: timeData
                },
                series: [{
                    data: memoryData
                }]
            });

            // 模拟进程数据
            const processes = [
                { name: '浏览器内核', value: totalMemory * 0.4 },
                { name: 'JavaScript引擎', value: totalMemory * 0.25 },
                { name: 'DOM渲染', value: totalMemory * 0.15 },
                { name: '网络请求', value: totalMemory * 0.1 },
                { name: '插件进程', value: totalMemory * 0.05 },
                { name: '其他', value: totalMemory * 0.05 }
            ];

            // 更新饼图
            processChart.setOption({
                series: [{
                    data: processes
                }]
            });
        }
    }

    // 格式化内存大小
    function formatMemorySize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 监控按钮点击事件
    $('.monitor-btn').on('click', function() {
        const $btn = $(this);
        const $container = $('.memory-chart-container');
        
        if ($container.hasClass('show')) {
            // 关闭监控
            $container.removeClass('show');
            $btn.removeClass('active');
            
            // 停止更新
            if (memoryTimer) {
                clearInterval(memoryTimer);
                memoryTimer = null;
            }
            
            // 清空数据
            memoryData = [];
            timeData = [];
            processData = [];
        } else {
            // 显示监控
            $container.addClass('show');
            $btn.addClass('active');
            
            // 初始化图表
            if (!memoryChart || !processChart) {
                initMemoryCharts();
            }
            
            // 开始更新数据
            updateMemoryData();
            memoryTimer = setInterval(updateMemoryData, 1000);
        }
    });

    // 关闭按钮点击事件
    $('.chart-close').on('click', function() {
        $('.monitor-btn').click();
    });

    // 窗口大小改变时调整图表大小
    $(window).on('resize', function() {
        if (memoryChart) {
            memoryChart.resize();
        }
        if (processChart) {
            processChart.resize();
        }
    });

    // 天气图表相关变量
    let weatherChart = null;
    let currentWeatherData = null;

    // 模拟珠海历史天气数据生成函数
    function generateHistoricalWeatherData(year, month) {
        const daysInMonth = new Date(year, month, 0).getDate();
        
        // 根据珠海气候特点生成模拟数据
        const seasonalTemp = {
            winter: { min: 10, max: 20 },  // 冬季（12-2月）
            spring: { min: 15, max: 25 },  // 春季（3-5月）
            summer: { min: 25, max: 35 },  // 夏季（6-8月）
            autumn: { min: 20, max: 30 }   // 秋季（9-11月）
        };

        const seasonalRain = {
            winter: { min: 0, max: 30 },   // 冬季降水较少
            spring: { min: 20, max: 100 },  // 春季降水增多
            summer: { min: 50, max: 200 },  // 夏季降水最多
            autumn: { min: 30, max: 150 }   // 秋季降水较多
        };

        let season;
        switch(month) {
            case 12:
            case 1:
            case 2:
                season = 'winter';
                break;
            case 3:
            case 4:
            case 5:
                season = 'spring';
                break;
            case 6:
            case 7:
            case 8:
                season = 'summer';
                break;
            default:
                season = 'autumn';
        }

        const tempRange = seasonalTemp[season];
        const rainRange = seasonalRain[season];

        return {
            dates: Array.from({length: daysInMonth}, (_, i) => 
                `${year}-${String(month).padStart(2, '0')}-${String(i + 1).padStart(2, '0')}`
            ),
            temperatures: Array.from({length: daysInMonth}, () => 
                Math.round((Math.random() * (tempRange.max - tempRange.min) + tempRange.min) * 10) / 10
            ),
            rainfall: Array.from({length: daysInMonth}, () => 
                Math.round((Math.random() * (rainRange.max - rainRange.min) + rainRange.min) * 10) / 10
            ),
            humidity: Array.from({length: daysInMonth}, () => 
                Math.round(Math.random() * 30 + 60)  // 珠海湿度较大，60-90%
            ),
            windSpeed: Array.from({length: daysInMonth}, () => 
                Math.round(Math.random() * 20 + 5)   // 5-25km/h
            )
        };
    }

    // 初始化天气图表
    function initWeatherChart() {
        const chartDom = document.getElementById('weatherChart');
        weatherChart = echarts.init(chartDom);
        
        // 获取当前日期
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth() + 1;
        
        // 设置日期选择器的默认值
        $('#weatherMonth').val(`${currentYear}-${String(currentMonth).padStart(2, '0')}`);
        $('#weatherYear').val(currentYear);
        
        // 生成初始数据
        updateWeatherData(currentYear, currentMonth);
    }

    // 更新天气数据和图表
    function updateWeatherData(year, month) {
        currentWeatherData = generateHistoricalWeatherData(year, month);
        
        const option = {
            title: {
                text: `珠海${year}年${month}月天气数据`,
                left: 'center',
                top: 0
            },
            tooltip: {
                trigger: 'axis',
                formatter: function(params) {
                    let result = params[0].axisValue + '<br/>';
                    params.forEach(param => {
                        let value = param.value;
                        let unit = '';
                        switch(param.seriesName) {
                            case '温度':
                                unit = '°C';
                                break;
                            case '降水量':
                                unit = 'mm';
                                break;
                            case '湿度':
                                unit = '%';
                                break;
                            case '风速':
                                unit = 'km/h';
                                break;
                        }
                        result += param.marker + param.seriesName + ': ' + value + unit + '<br/>';
                    });
                    return result;
                }
            },
            legend: {
                data: ['温度', '降水量', '湿度', '风速'],
                top: 30
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: 80,
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: currentWeatherData.dates,
                axisLabel: {
                    formatter: function(value) {
                        return value.split('-')[2];
                    }
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '温度(°C)/湿度(%)',
                    position: 'left'
                },
                {
                    type: 'value',
                    name: '降水量(mm)',
                    position: 'right',
                    offset: 0
                },
                {
                    type: 'value',
                    name: '风速(km/h)',
                    position: 'right',
                    offset: 80
                }
            ],
            series: [
                {
                    name: '温度',
                    type: 'line',
                    smooth: true,
                    data: currentWeatherData.temperatures,
                    itemStyle: {
                        color: '#FF9F43'
                    }
                },
                {
                    name: '降水量',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: currentWeatherData.rainfall,
                    itemStyle: {
                        color: '#54A0FF'
                    }
                },
                {
                    name: '湿度',
                    type: 'line',
                    smooth: true,
                    data: currentWeatherData.humidity,
                    itemStyle: {
                        color: '#00D2D3'
                    }
                },
                {
                    name: '风速',
                    type: 'line',
                    smooth: true,
                    yAxisIndex: 2,
                    data: currentWeatherData.windSpeed,
                    itemStyle: {
                        color: '#5F27CD'
                    }
                }
            ]
        };
        
        weatherChart.setOption(option);
    }

    // 日期选择事件处理
    $('#weatherMonth, #weatherYear').on('change', function() {
        const year = parseInt($('#weatherYear').val());
        const month = parseInt($('#weatherMonth').val().split('-')[1]);
        updateWeatherData(year, month);
    });

    // 导出图表为图片
    function exportChart() {
        const year = $('#weatherYear').val();
        const month = $('#weatherMonth').val().split('-')[1];
        
        const url = weatherChart.getDataURL({
            pixelRatio: 2,
            backgroundColor: '#fff'
        });
        
        const link = document.createElement('a');
        link.download = `珠海${year}年${month}月天气数据.png`;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // 生成PDF预览
    async function generatePDF() {
        const year = $('#weatherYear').val();
        const month = $('#weatherMonth').val().split('-')[1];
        
        try {
            // 显示加载状态
            const $previewOverlay = $('.pdf-preview-overlay');
            const $pdfViewer = $('#pdfViewer');
            const $loadingIndicator = $('<div class="loading-indicator">正在生成PDF，请稍候...</div>');
            
            $pdfViewer.attr('src', '');
            $previewOverlay.append($loadingIndicator)
                          .css('display', 'flex')
                          .fadeIn(300);
            
            // 预先渲染图表
            weatherChart.resize();
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // 创建PDF文档
            const doc = new jspdf.jsPDF('landscape', 'mm', 'a4', {
                filters: ['ASCIIHexEncode']
            });
            
            // 设置字体
            doc.setFont('courier', 'normal');
            doc.setFontSize(20);
            
            // 预渲染所有Canvas元素
            const [titleCanvas, detailCanvas, chartCanvas] = await Promise.all([
                // 标题Canvas
                (async () => {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    ctx.font = '20px Arial';
                    const title = `珠海${year}年${month}月天气数据报告`;
                    const titleWidth = ctx.measureText(title).width;
                    canvas.width = titleWidth;
                    canvas.height = 30;
                    ctx.font = '20px Arial';
                    ctx.fillStyle = '#000000';
                    ctx.fillText(title, 0, 20);
                    return canvas;
                })(),
                
                // 详细数据标题Canvas
                (async () => {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    ctx.font = '16px Arial';
                    const detailTitle = '详细数据';
                    const detailWidth = ctx.measureText(detailTitle).width;
                    canvas.width = detailWidth;
                    canvas.height = 24;
                    ctx.font = '16px Arial';
                    ctx.fillStyle = '#000000';
                    ctx.fillText(detailTitle, 0, 16);
                    return canvas;
                })(),
                
                // 图表Canvas
                (async () => {
                    const chartElement = document.getElementById('weatherChart');
                    return await html2canvas(chartElement, {
                        scale: 2,
                        backgroundColor: '#ffffff',
                        logging: false,
                        useCORS: true,
                        allowTaint: true,
                        width: chartElement.offsetWidth,
                        height: chartElement.offsetHeight
                    });
                })()
            ]);
            
            // 添加标题
            const titleWidth = titleCanvas.width;
            const titleImgData = titleCanvas.toDataURL('image/png');
            doc.addImage(titleImgData, 'PNG', (297 - titleWidth * 0.3) / 2, 10, titleWidth * 0.3, 10);
            
            // 添加图表
            const imgData = chartCanvas.toDataURL('image/png');
            const pageWidth = doc.internal.pageSize.getWidth();
            const imgWidth = pageWidth - 20;
            const imgHeight = (chartCanvas.height * imgWidth) / chartCanvas.width;
            doc.addImage(imgData, 'PNG', 10, 30, imgWidth, imgHeight);
            
            // 添加数据表格页
            doc.addPage();
            
            // 添加详细数据标题
            const detailWidth = detailCanvas.width;
            const detailImgData = detailCanvas.toDataURL('image/png');
            doc.addImage(detailImgData, 'PNG', (297 - detailWidth * 0.3) / 2, 10, detailWidth * 0.3, 8);
            
            // 创建表格数据
            const headers = [['日期', '温度(°C)', '降水量(mm)', '湿度(%)', '风速(km/h)']];
            const data = currentWeatherData.dates.map((date, index) => [
                date,
                currentWeatherData.temperatures[index].toFixed(1),
                currentWeatherData.rainfall[index].toFixed(1),
                currentWeatherData.humidity[index],
                currentWeatherData.windSpeed[index]
            ]);
            
            // 添加表格
            doc.autoTable({
                head: headers,
                body: data,
                startY: 30,
                theme: 'grid',
                styles: {
                    font: 'courier',
                    fontSize: 8,
                    cellPadding: 2,
                    overflow: 'linebreak'
                },
                headStyles: {
                    fillColor: [102, 126, 234],
                    textColor: 255,
                    fontSize: 10,
                    fontStyle: 'bold'
                },
                alternateRowStyles: {
                    fillColor: [245, 247, 250]
                },
                margin: { top: 30 }
            });
            
            // 生成PDF并显示
            const pdfBlob = doc.output('blob');
            const pdfUrl = URL.createObjectURL(pdfBlob);
            
            // 移除加载提示并显示PDF
            $loadingIndicator.remove();
            $pdfViewer.attr('src', pdfUrl);
            
        } catch (error) {
            console.error('生成PDF时发生错误:', error);
            alert(`生成PDF预览时发生错误: ${error.message}`);
            $('.pdf-preview-overlay').fadeOut(300);
        }
    }

    // 天气按钮点击事件
    $('.weather-btn').on('click', function() {
        const $btn = $(this);
        const $container = $('.weather-chart-container');
        
        if ($container.hasClass('show')) {
            // 关闭图表
            $container.removeClass('show');
            $btn.removeClass('active');
        } else {
            // 显示图表
            $container.addClass('show');
            $btn.addClass('active');
            
            // 初始化图表
            if (!weatherChart) {
                initWeatherChart();
            }
        }
    });

    // 导出按钮点击事件
    $('.export-btn').on('click', exportChart);

    // PDF预览按钮点击事件
    $('.preview-pdf-btn').on('click', generatePDF);

    // 关闭按钮点击事件
    $('.weather-chart-container .chart-close').on('click', function() {
        $('.weather-btn').click();
    });

    // PDF预览关闭按钮点击事件
    $('.pdf-close-btn').on('click', function() {
        $('.pdf-preview-overlay').fadeOut(300);
    });

    // 窗口大小改变时调整图表大小
    $(window).on('resize', function() {
        if (weatherChart) {
            weatherChart.resize();
        }
    });
});